package cn.zhc.com.http.upload;


import cn.zhc.com.http.listener.OnHttpUploadListener;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Created by zhouhongchun on 2017/8/8.
 */

public class UploadFileRequestBody extends RequestBody {


    protected RequestBody mRequestBody;
    protected OnHttpUploadListener listener;

    protected CountingSink countingSink;
    protected int fileTag;
    protected int IDUrl;

    public UploadFileRequestBody(RequestBody mRequestBody, OnHttpUploadListener listener, int fileTag, int IDUrl) {
        this.mRequestBody = mRequestBody;
        this.listener = listener;
        this.fileTag = fileTag;
        this.IDUrl = IDUrl;
    }


    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    @Override
    public long contentLength() {
        try {
            return mRequestBody.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {

        countingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(countingSink);

        mRequestBody.writeTo(bufferedSink);

        bufferedSink.flush();
    }

    protected final class CountingSink extends ForwardingSink {

        private long bytesWritten = 0;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);

            bytesWritten += byteCount;
            if (listener != null){
                listener.onUploadProgress(bytesWritten, contentLength(), fileTag, IDUrl);
            }

        }

    }

}
